#pragma once
#include <iostream>
#include <cstring>
#include <string>
#include <functional>
#include "nocopy.hpp" //禁止拷贝
#include "Log.hpp"
#include "ip_net_address.hpp"
#include "dict.hpp"

// OS
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

static const int gsockfd = -1;
static const uint16_t gsockport = 8888; // 随便给当前进程指定的端口号

using func_t = std::function<std::string(std::string)>; // 封装/重命名 函数指针

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR
};

class UdpServer : public NoCopy
{
public:
    UdpServer(func_t func)
        : _sockfd(gsockfd), _isrunning(false), _gsockport(gsockport), _func(func)
    {
    }

    // void InitServer(std::string &ip, uint16_t port)
    void InitServer(uint16_t port)
    {
        // 打开socket文件
        int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd < 0)
        {
            LOG(FATAL, "socked fail");
            exit(SOCKET_ERROR);
        }
        _sockfd = sockfd;
        uint len = sizeof(sockaddr_in);
        // 填充sockaddr_in对象
        struct sockaddr_in local_socket;
        bzero(&local_socket, sizeof(local_socket)); // memset(&local_sock, sizeof(local_sock), '\0');//初始化
        local_socket.sin_family = AF_INET;
        local_socket.sin_port = htons(port);
        // local_socket.sin_addr.s_addr = inet_addr(ip.c_str());
        local_socket.sin_addr.s_addr = INADDR_ANY; // 任意ip绑定

        // sockaddr_in对象 和 socket在OS层面上 bind
        int re = bind(_sockfd, (struct sockaddr *)&local_socket, len);
        if (re == -1)
        {
            LOG(FATAL, "bind fail");
            exit(BIND_ERROR);
        }
    }

    void Start()
    {
        _isrunning = true;

        // 接收客户端的sockaddr_in对象
        struct sockaddr_in cli_socket;
        uint len = sizeof(cli_socket);
        char buffer[1024] = {0}; // 用来接收的空间； 通过_sockfd文件缓冲区接收
        while (_isrunning)
        {
            // 接收
            int n = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&cli_socket, (socklen_t *)&len);
            if (n >= 0) // 实际接收的字节数
            {
                Log(INFO, "recvfrom success");
                InetAdress inet_addr(cli_socket); // 通过封装构造对象，获得hostip,hostport
                std::cout << "client: [" << inet_addr.Ip() << ":" << inet_addr.Port() << "]" << std::endl;
                // 准备发送
                buffer[n] = '\0';
                std::string result = _func(buffer);

                // std::cout << buffer << std::endl; // 打印
                std::string send_str = "This is client data:";
                send_str += result;
                int n = sendto(_sockfd, send_str.c_str(), send_str.size(), 0, (struct sockaddr *)&cli_socket, len);
                if (n < 0) // 比//n == -1 增加了健壮性/鲁棒性
                {
                    Log(FATAL, "sendto fail");
                    exit(-1);
                }
            }
            else
            {
                Log(FATAL, "recvfrom fail");
                exit(-1);
            }
        }
       _isrunning = false;     
    }

    ~UdpServer()
    {
        if (_sockfd > gsockfd)
            close(_sockfd);
    }

private:
    int _sockfd;
    bool _isrunning;
    uint16_t _gsockport;
    func_t _func; // 回调函数--翻译
};
